package com.example.gcmtest1;

import com.example.gcmtest1.youtube.YoutubeSQLRecord;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySqlHelper extends SQLiteOpenHelper {

	private String logName = "MySqlHelper";
	private SQLiteDatabase db;
	
	public MySqlHelper(Context context) {
		super(context, "mydb1.db", null, 1);
		db = this.getWritableDatabase();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		/*
		String sql = "create table test(id integer primary key, stt text);";
		db.execSQL(sql);
		Log.d(logName, "executed: " + sql);
		
		sql = "create table test2(id integer primary key, stt text);";
		db.execSQL(sql);
		Log.d(logName, "executed: " + sql);
		*/

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}
	
	public YoutubeSQLRecord[] getAllRecords() {
		Cursor cursor = this.db.rawQuery("select * from youtube", null); 
		if (cursor.getCount() != 0) {
			YoutubeSQLRecord[] rr = new YoutubeSQLRecord[cursor.getCount()]; 
			cursor.moveToFirst();
			
			while (!cursor.isAfterLast()) {
				YoutubeSQLRecord r = YoutubeSQLRecord.cursorToRecord(cursor);
				cursor.moveToNext();
			}
			
			return(rr);
		}
		
		return(null);
	}
		
	public YoutubeSQLRecord getDetailById(long id) {
		Cursor cursor = this.db.rawQuery("select * from youtube where id=?", new String[] {String.valueOf(id)}); 
		if (cursor.getCount() != 0) {
			YoutubeSQLRecord r = YoutubeSQLRecord.cursorToRecord(cursor);
			return(r);
		}
		
		return(null);
	}
	
	public void insertYoutube(YoutubeSQLRecord r) {
		long id;
		if (r.getId() == -1) {
			id = System.currentTimeMillis();	
		} else {
			id = r.getId();
		}
		
		ContentValues values = new ContentValues();
		values.put("id", id);
		values.put("original_url", r.getOriginalUrl());
		values.put("title", r.getTitle());
		values.put("content_type", r.getContentType());
		values.put("content_length", r.getContentLength());
		values.put("last_byte", r.getLastByte());
		values.put("file_location", r.getFileLocation());
		values.put("final_url", r.getFinalUrl());
		values.put("status", r.getStatus());
		
		long insertId = this.db.insert("youtube", null, values);
		
		Log.d(logName, "inserted 1 youtube record, id=" + String.valueOf(id) + ", insertId=" + String.valueOf(insertId));
		
	}
	

}
